# -*- coding: utf-8 -*-
import _thread
import cgitb
import importlib
import os
import random
import sys

from PyQt5.QtWidgets import QApplication
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger

from compoments.mainWindowImpl import MainWindowImpl
from compoments.trayIcon import TrayIcon
from compoments.workFillWindowImpl import WorkFillWindowImpl
from service.workHourService import WorkHourService
from util import aesUtil, configJsonUtil, startUpUtil
from util.globalContext import Context
from util.loggerFactory import Logger

logger = Logger()


class App(object):

    def __init__(self):
        cgitb.enable(logdir="Log", format="text")
        os.putenv("QTWEBENGINE_REMOTE_DEBUGGING", "9223")
        os.putenv("QTWEBENGINE_CHROMIUM_FLAGS", "-single-process")
        app = QApplication(sys.argv)
        # 加载资源
        importlib.import_module("resources.assert_rc")
        self.mainWindowImpl = WorkFillWindowImpl()
        Context().mainWindowImpl = self.mainWindowImpl
        self.icon = TrayIcon(self.mainWindowImpl)
        Context().trayIcon = self.icon

        # self.mainWindowImpl1 = MainWindowImpl()

        _thread.start_new_thread(self.start_work_hour_job, ())
        sys.exit(app.exec_())

    def start_work_hour_job(self):
        logger.info("启动工时填报任务")
        sched = BlockingScheduler()
        # 周一至周五下班开始任务
        config = configJsonUtil.get_config()
        day_of_week = config['work_hour']['day_of_week']
        hour_ = config['work_hour']['hour']
        hour = random.choice(hour_.split(','))
        minute_ = config['work_hour']['minute']
        minutes = minute_.split('-')
        minute = str(random.randint(int(minutes[0]), int(minutes[1])))
        second = str(random.randint(0, 60))
        logger.info("当前填报执行时间 天：{}，小时：{}， 分钟：{}，秒：{}".format(day_of_week, hour, minute, second))
        trigger = CronTrigger(day_of_week=day_of_week, hour=hour, minute=minute, second=second)
        sched.add_job(self.start_job, trigger)  # 根据需要进行设置
        sched.start()

    def start_job(self):
        logger.info("准备开始填报工时")
        workHourService = WorkHourService()
        workHourService.fill_work_hour_random()
        # workHourService.query_work_hour()
        workHourService.audit_work_hour()


if __name__ == "__main__":
    App()
